﻿using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;

namespace rpxnow_library.rpxnowapi.requests
{
    internal class Json : rpxnow_library.rpxnowapi.requests.Iapi
    {
        rpxnow_library.rpxnowapi.responses.Auth_info Iapi.auth_info(string token)
        {
            rpxnow_library.rpxnowapi.responses.Auth_info result = new rpxnow_library.rpxnowapi.responses.Auth_info();

            var query = new Dictionary<string, string>();
            query.Add("token", token);

            JObject o = Json.ApiCall("auth_info", query);

            var profile = o["profile"];
            if (profile != null)
            {
                result.profile.identifier = (string)profile["identifier"];
                result.profile.providerName = (string)profile["providerName"];
                result.profile.verifiedEmail = (string)profile["verifiedEmail"];

                var name = profile["name"];
                if (name != null)
                {
                    result.profile.name.givenName = (string)name["givenName"];
                    result.profile.name.familyName = (string)name["familyName"];
                    result.profile.name.formatted = (string)name["formatted"];
                }

                var address = profile["address"];
                if (address != null)
                {
                    result.profile.address.region = (string)address["region"];
                    result.profile.address.country = (string)address["country"];
                    result.profile.address.locality = (string)address["locality"];
                }

                result.profile.photo = (string)profile["photo"];

                result.profile.displayName = (string)profile["displayName"];
                result.profile.preferredUsername = (string)profile["preferredUsername"];
                result.profile.email = (string)profile["email"];

                result.profile.url = (string)profile["url"];
            }

            var err = o["err"];
            if (err != null)
            {
                result.err.msg = (string)profile["msg"];

                int code;
                if (int.TryParse((string)profile["code"], out code))
                    result.err.code = code;
            }

            result.stat = (string)o["stat"];

            return result;
        }

        static private JObject ApiCall(string methodName, IDictionary<string, string> partialQuery)
        {
            string jsonResponse = Pipeline.ApiCall(methodName, partialQuery, "json");

            return JObject.Parse(jsonResponse);
        }
    }
}
